import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

///本页面主要展示获取图片，从拍照/相册
class ImagePickerPage extends StatefulWidget {
  @override
  _ImagePickerPageState createState() => _ImagePickerPageState();
}

class _ImagePickerPageState extends State<ImagePickerPage> {
  List<File> _images = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('图片选择'),
      ),
      body: Center(
        child: Wrap(
          spacing: 5,
          runSpacing: 5,
          children: _genImages(),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _pickImage,
        child: Icon(Icons.add_a_photo),
        tooltip: '选择图片',
      ),
    );
  }

  void _pickImage() {
    showModalBottomSheet(
        context: context,
        builder: (context) => Container(
              height: 120,
              child: Column(
                children: [
                  _buildItem('拍照', true),
                  _buildItem('相机', false),
                ],
              ),
            ));
  }

  _buildItem(String title, bool isTakePhoto) {
    return GestureDetector(
      onTap: () => _getImage(isTakePhoto),
      child: ListTile(
        leading:
            isTakePhoto ? Icon(Icons.camera_alt) : Icon(Icons.photo_library),
        title: Text(title),
      ),
    );
  }

  Future _getImage(bool isTakePhoto) async {
    Navigator.pop(context);
    var image = await ImagePicker().getImage(
      source: isTakePhoto ? ImageSource.camera : ImageSource.gallery,
    );
    if (image != null) {
      setState(() {
        _images.add(File(image.path));
      });
    }
  }

  _genImages() {
    return _images.map((e) => Stack(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(6),
              child: Image.file(
                e,
                width: 120,
                height: 90,
                fit: BoxFit.fill,
              ),
            )
          ],
        )).toList();
  }
}
